const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV,
})

exports.main = async (event) => {
	try {
		const { id } = event

		const DB = cloud.database()

		const getArticleInfo = await DB.collection('gn_article').doc(id).get()

		const spaceid = getArticleInfo.data.belong_space
		// 删除article
		await DB.collection('gn_article').doc(id).remove()
		// 从space中移除
		const getSpaceInfoForUpdate = await DB.collection('gn_space').doc(spaceid).get()
		const newSpaceArticleList = getSpaceInfoForUpdate.data.article
        const index = newSpaceArticleList.findIndex(art => art._id === id)
        newSpaceArticleList.splice(index, 1)
        await DB.collection('gn_space').doc(spaceid).update({
            data: {
                article: newSpaceArticleList
            }
        })
        const getSpaceInfo = await DB.collection('gn_space').doc(spaceid).get()

		return {
			data: {
                space: getSpaceInfo.data,
            },
			code: 0,
			msg: '删除成功',
		}
	} catch (err) {
		throw err
	}
}
